from datetime import datetime
from flask import Flask
from flask_marshmallow import Marshmallow
from marshmallow import Schema,fields,validate,post_dump,post_load,pre_dump,pre_load
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"]="mysql://root:123@127.0.0.1:3306/mofangapp?charset=utf8mb4"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy()
db.init_app(app)

ma = Marshmallow()
ma.init_app(app)

class User(db.Model):
    __tablename__ = "tb_user"
    id = db.Column(db.Integer, primary_key=True, comment="主键ID")
    name = db.Column(db.String(255), index=True, comment="用户名")
    age = db.Column(db.Integer, comment="年龄")
    password = db.Column(db.String(255), comment="登录密码")
    mobile = db.Column(db.String(20), comment="手机号")
    created_time = db.Column(db.DateTime, default=datetime.now, comment="创建时间")

    def __repr__(self):
        return "<%s: %s>" % (self.__class__.__name__, self.name)


class UserSchema(Schema):
    name = fields.String(validate=validate.Length(min=1))
    age = fields.Integer(required=True)
    password = fields.Str(load_only=True) # 相当于只写字段 "write-only"
    # created_time = fields.DateTime(dump_only=True) # 相当于只读字段 "read-only"
    created_time = fields.DateTime(format='%Y-%m-%d %H:%M:%S')
    mobile = fields.String()

    @pre_load
    def pre_load(self,data,**kwargs):
        """反序列化的前置钩子，会在数据验证之前执行"""
        data["created_time"] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        return data

    @post_load
    def post_load(self,data,**kwargs):
        """反序列化钩子方法"""
        data["password"] = generate_password_hash(data["password"])
        return User(**data)

    @post_dump
    def post_dump(self,data,**kwargs):
        """序列化钩子方法"""
        data["number"] = 1000
        data["mobile"] = data["mobile"][:3]+"****"+data["mobile"][-4:]
        return data

@app.route("/")
def index():
    user_data = {"name": "小明", "age": 20,"password":"123456","mobile":"13312345678"}
    us = UserSchema()
    # 反序列化
    instance = us.load(user_data)
    print(instance) # <User: 小明>
    print(instance.created_time) # <User: 小明>

    # 序列化
    data = us.dump(instance)
    print(data)
    return "hello"

if __name__ == '__main__':
    app.run(debug=True,host="0.0.0.0",port=5999)